package com.zhw.goshopping.controller;

import com.zhw.goshopping.common.utils.JsonUtils;
import com.zhw.goshopping.utils.FastDFSUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * Create by zhaihongwei on 2018/3/23
 * 图片上传Controller
 */
@Controller
public class PictureController {

    @Value("${server_url}")
    private String server_url;

    @RequestMapping("/pic/upload")
    @ResponseBody
    public String pictureUpload(MultipartFile uploadFile) {
        try {
            // 接受上传路径
            // 取扩展名
            String originalFilename = uploadFile.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            // 上传文件到FastDFS服务器
            String conf = "fdfs_client.conf";
            FastDFSUtils fastDFSUtils = new FastDFSUtils(conf);
            String url = fastDFSUtils.uploadFile(uploadFile.getBytes(),extName);
            // 响应上传文件的url
            url = server_url + url;
            System.out.println(url);
            // 返回数据KindEditor
            Map result = new HashMap();
            result.put("error",0);
            result.put("url",url);
            return JsonUtils.objectToJson(result);
        } catch (Exception e) {
            e.printStackTrace();
            // 返回数据KindEditor
            Map result = new HashMap();
            result.put("error",0);
            result.put("message","图片上传失败！");
            return JsonUtils.objectToJson(result);
        }

    }
}
